<?php

declare(strict_types=1);

namespace App\Common\Service\Affiliate;

class WphService extends AbstractAffiliateService
{
    public function getAuthUrl(array $params): string
    {
        $domain = $this->getDomain();
        $appKey = $this->getAppKeyAndSecret()['appKey'];
        $callBackUrl = hyperf_url("callback/wphLoginCallback/uid/{uid}/main_uid/{main_uid}/suc_jump/{suc_jump}/type/{type}",[
            'uid' => $params['uid'],
            'main_uid' => $params['main_uid'],
            'suc_jump' => urlencode($params['url']),
            'type' => $params['type'],
        ],$domain);
        $urls = 'https://auth.vip.com/oauth2/authorize?client_id='.$appKey.'&response_type=code&redirect_uri=' . urlencode($callBackUrl);
        return $urls;
    }

    public function getAppKeyName(): string
    {
        return 'wph_app_key';
    }

    public function getAppSecretName(): string
    {
        return 'wph_app_secret';
    }

    /**
     * 通过code获取access_token
     * @param $code
     * @return false|mixed
     */
    public function getAccessToken($code): mixed
    {
        $config = $this->getAppKeyAndSecret();
        $appKey = $config['appKey'];
        $appSecret = $config['appSecret'];
        $redirecturi = 'http://www.myxcxdz/com';

        $data = [
            'grant_type' => 'authorization_code',
            'client_id' => $appKey,
            'client_secret' => $appSecret,
            'redirect_uri' => $redirecturi,
            'request_client_ip' => get_client_ip(),
            'code' => $code,
        ];

        $url = 'https://auth.vip.com/oauth2/token?'.http_build_query($data);

        return $this->post($url,[
            'app_key' => $appKey,
            'app_secret' => $appSecret,
            'grant_type' => 'authorization_code',
            'code' => $code,
        ]);
    }
}